package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone) {
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误！");
        }
        String numbers = RandomUtil.randomNumbers(6);
        stringRedisTemplate.opsForValue().set(phone, numbers, 2, TimeUnit.MINUTES);
        log.info("生成验证码成功！{}", numbers);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm) {
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误！");
        }
        // 从 redis 中获取验证码进行校验
        String cacheCode = stringRedisTemplate.opsForValue().get(phone);
        // 判断比较
        String code = loginForm.getCode();
        if (cacheCode == null || !cacheCode.equals(code)) {
            return Result.fail("验证码错误！");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        User one = getOne(wrapper);
        if (one == null) {
            one = createUserWithPhone(phone);
        }
        // 保存信息到 redis
        // uuid
        String token = UUID.randomUUID().toString(true);
        // 将user 转为 hash 结构进行存储
        UserDTO userDTO = BeanUtil.copyProperties(one, UserDTO.class);
        Map<String, Object> map = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create() // 创建空的选项器
                        .setIgnoreNullValue(true) // 忽略空值
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        stringRedisTemplate.opsForHash().putAll(token, map);
        stringRedisTemplate.expire(token, 30, TimeUnit.MINUTES);
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        // 获取用户
        Long userId = UserHolder.getUser().getId();
        // 获取日期
        LocalDateTime dateTime = LocalDateTime.now();
        // 拼接key
        String keySuffix = dateTime.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = RedisConstants.USER_SIGN_KEY + userId + keySuffix;
        // 获取今天是本月的第几天
        int dayOfMonth = dateTime.getDayOfMonth();
        // 写入redis setbit key
        Boolean bit = stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        return Result.ok(bit);
    }

    @Override
    public Result signCount() {
        // 获取用户
        Long userId = 5L;
        // 获取日期
        LocalDateTime dateTime = LocalDateTime.now();
        // 拼接key
        String keySuffix = dateTime.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = RedisConstants.USER_SIGN_KEY + userId + keySuffix;
        // 获取今天是本月的第几天
        int dayOfMonth = dateTime.getDayOfMonth();

        // 1. 获取本月截至今天的所有签到记录，返回一个十进制数。
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key, BitFieldSubCommands.create().get(
                                // 无符号数，获取到第几天
                                BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                        // 从第几天开始
                        .valueAt(0)
        );
        if (result == null || result.isEmpty()) {
            // 没有任何签到结果
            return Result.ok(0);
        }
        Long num = result.get(0);
        if (num == null || num == 0) {
            return Result.ok(0);
        }
        // 2. 循环遍历
        int count = 0;
        while (true) {
            // 1. 用这个数字与 1 做运算，得到数字的最后一个 bit 位
            long n = num & 1;
            // 2. 判断这个 bit 位是不是 0
            if (n == 0) {
                // 3. 如果是 0 ，说明未签到，结束
                break;
            }
            // 4. 如果不为 0，说明签到了，计数 + 1
            count++;
            // 5. 把数字右移，抛弃最后一个 bit 位，继续下一个
            num >>>= 1;
        }
        return Result.ok(count);
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName("昵称_" + RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
